package com.affaris.controller;


import com.affaris.common.QueryPageParam;
import com.affaris.common.Result;
import com.affaris.entity.Organizations;
import com.affaris.entity.Users;
import com.affaris.service.OrganizationsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lucas
 * @since 2023-05-15
 */
@RestController
@RequestMapping("/organizations")
public class OrganizationsController {

    @Autowired
    private OrganizationsService organizationsService;

    //新增
    @PostMapping("/save")
    public Result save(@RequestBody Organizations organizations) {
        return organizationsService.save(organizations) ? Result.suc() : Result.fail();
    }

    //删除
    @GetMapping("/delete")
    public Result delete(@RequestParam String id) {

        return organizationsService.removeById(id) ? Result.suc() : Result.fail();
    }

    //更新
    @PostMapping("/update")
    public Result update(@RequestBody Organizations organizations) {
        return organizationsService.updateById(organizations) ? Result.suc() : Result.fail();
    }

    //查询
    @PostMapping("/page")
    public Result page(@RequestBody QueryPageParam queryPageParam) {
        HashMap param = queryPageParam.getParam();
        String name = (String) param.get("name");
        String code = (String) param.get("code");

        System.out.println("num==" + queryPageParam.getPageNum());
        System.out.println("size==" + queryPageParam.getPageSize());

        Page<Organizations> page = new Page();
        page.setCurrent(queryPageParam.getPageNum());
        page.setSize(queryPageParam.getPageSize());

        LambdaQueryWrapper<Organizations> lambdaQueryWrapper = new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(name) && !"null".equals(name)) {
            lambdaQueryWrapper.like(Organizations::getName, name);
        }
        if (StringUtils.isNotBlank(code)) {
            lambdaQueryWrapper.eq(Organizations::getCode, code);
        }

        IPage result = organizationsService.page(page, lambdaQueryWrapper);
        return Result.suc(result.getRecords(), result.getTotal());
    }

    //编号唯一验证
    @GetMapping("/findByCode")
    public Result findByCode(@RequestParam String code) {
        List list = organizationsService.lambdaQuery().eq(Organizations::getCode, code).list();
        return list.size() > 0 ? Result.suc(list) : Result.fail();
    }

    @GetMapping("/list")
    public Result list() {
        List list = organizationsService.list();
        return Result.suc(list);
    }

}
